import axios from 'axios'
import {ElMessage} from 'element-plus'
import store from '@/store'
import {toast} from "@/hook/toast";
import router from "@/router";

const codeEnum = {
    200: 'success',
    201: 'warning',
    202: 'error'
}

const instance = axios.create({
    baseURL:'/api',
    timeout: 5000,
})

instance.interceptors.request.use(config => {
    const {hasLogin, token} = store.getters
    if (hasLogin) {
        config.headers.token = token
    }
    return config
}, error => {
    return Promise.reject(error)
})
instance.interceptors.response.use(response => {
    const {data} = response
    const {code, msg} = data
    if (code !== 1) {
        if (code === 401) { // no login
            toast({title: '登录后可进行更多操作', type: 'error'})
            router.replace({name: 'login'}).catch(null)
            return Promise.reject(data)
        }
        if (code === 403) { // no login
            toast({title: '无权限访问', type: 'error'})
            // router.replace({name: 'login'}).catch(null)
            // return Promise.reject(data)
        }
        ElMessage({
            type: 'error',
            message: msg,
            duration: 2 * 1000,
        })
        return Promise.reject(data)
    }
    return data
}, error => {
    const {data} = error.response
    const {code, msg} = data
    if (code !== 1) {
        if (code === 403) { // no login
            toast({title: '无权限访问', type: 'error'})
            // router.replace({name: 'login'}).catch(null)
            // return Promise.reject(data)
        }
        ElMessage({
            type: 'error',
            message: msg,
            duration: 2 * 1000,
        })
        router.push('/profile').catch(() => null)
        return Promise.reject(data)
    }
    return data
    console.log('响应失败!', error)
    return Promise.reject(error)
})

export default instance
